<?php

namespace Cti\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class ApiController extends Controller
{
    /** 最多同步记录数 */
    const MAX_SYNC_ITEMS = 20;

    /** 数据类型 */
    const LOG_TYPE_IVR = 'ivr';
    const LOG_TYPE_SOUND = 'sound';

    /** 操作类型 */
    const LOG_ACTION_CTEATE = 'create';
    const LOG_ACTION_UPDATE = 'update';
    const LOG_ACTION_DELETE = 'delete';

    /**
     * 获取变化的列表
     *
     * @param int $myid      当前已处理的id
     * @param int $currentid 当前最新的id
     *
     * @return JsonResponse
     */
    public function changelogListAction($myid, $currentid)
    {
        if (!is_numeric($myid) || !is_numeric($currentid)) {
            return new JsonResponse(array(
                'code' => 400,
                'message' => 'myid和currentid必须都为数字'
            ));
        }

        if ($myid >= $currentid) {
            return new JsonResponse(array(
                'code' => 401,
                'message' => '当前处理的id大于等于待处理的id'
            ));
        }

        $conn = $this->get('doctrine.dbal.default_connection');
        $result = $conn->fetchAll(
            'SELECT id FROM cc_cti_change_logs WHERE id > :myid AND id <= :currentid',
            array(
                ':myid' => $myid,
                ':currentid' => $currentid
            )
        );
        $response = array();
        foreach ($result as $row) {
            $response[] = $row['id'];
        }

        return new JsonResponse(array(
            'code' => 200,
            'message' => 'ok',
            'data' => $response
        ));
    }

    /**
     * 同步数据
     *
     * @param int $id
     * @return bool|JsonResponse|Response
     */
    public function syncAction($id)
    {
        if (empty($id)) {
            return new JsonResponse(array(
                'code' => 400,
                'message' => 'id参数为空'
            ));
        }

        if (!is_numeric($id)) {
            return new JsonResponse(array(
                'code' => 401,
                'message' => 'id参数为非数字格式'
            ));
        }

        $conn = $this->get('doctrine.dbal.default_connection');
        $result = $conn->fetchAssoc(
            'SELECT id,vcc_id,log_type,log_action,table_id FROM cc_cti_change_logs WHERE id=:id LIMIT 1',
            array(':id' => $id)
        );

        if (empty($result)) {
            return new JsonResponse(array(
                'code' => 402,
                'message' => sprintf('id %s 对应的记录不存在', $id)
            ));
        }

        $logType = empty($result['log_type']) ? '' : $result['log_type'];
        switch ($logType) {
            case 'ivr':
                $response = $this->getIvr($result);
                return new JsonResponse(array(
                    'code' => 200,
                    'message' => 'ok',
                    'data' => $response
                ), Response::HTTP_OK, array(
                    'X-Cti-Sync-Type' => 'ivr',
                ));
                break;
            case 'sound':
                $response = $this->getSound($result);
                if ($response === false) {
                    return new JsonResponse();
                } else {
                    return $response;
                }
                break;
            default:
                return new JsonResponse();
                break;
        }
    }

    /**
     * 同步ivr信息
     *
     * @param array $result 同步记录信息
     *
     * @return bool|array
     */
    public function getIvr($result)
    {
        if (empty($result)) {
            return false;
        }
        $table_id = isset($result['table_id']) ? $result['table_id'] : 0;
        $log_action = empty($result['log_action']) ? '' : $result['log_action'];
        $conn = $this->get('doctrine.dbal.default_connection');

        switch ($log_action) {
            case self::LOG_ACTION_CTEATE:
            case self::LOG_ACTION_UPDATE:
                //查询指定记录的信息
                $ivr = $conn->fetchAssoc(
                    'SELECT ivr_id,vcc_id,ivr_code,ivr_info FROM win_ivr WHERE ivr_id=:ivr_id LIMIT 1',
                    array(
                        ':ivr_id' => $table_id
                    )
                );
                $ivrCode = empty($ivr['ivr_code']) ? '' : $ivr['ivr_code'];
                $ivrInfo = empty($ivr['ivr_info']) ? '' : $ivr['ivr_info'];
                break;
            case self::LOG_ACTION_DELETE:
                $ivrInfo = '';
                $ivrCode = 'ivr'.$result['vcc_id'].'_'.$table_id;
                break;
            default:
                $ivrInfo = '';
                $ivrCode = 'ivr'.$result['vcc_id'].'_'.$table_id;
                break;
        }

        return array(
            'id' => $result['id'],
            'vcc_id' => $result['vcc_id'],
            'log_type' => 'ivr',
            'log_action' => $log_action,
            'ivr_code' => $ivrCode,
            'ivr_info' => $ivrInfo
        );
    }

    /**
     * 同步语音文件
     *
     * @param array $result 需要同步的记录
     *
     * @return bool|Response
     */
    public function getSound($result)
    {
        if (empty($result)) {
            return false;
        }

        $log_action = isset($result['log_action']) ? $result['log_action'] : '';
        if ($log_action == 'delete') {
            return new Response('', Response::HTTP_OK, array(
                'X-Cti-Sync-Type' => 'sound',
                'X-Cti-Sync' => json_encode(array(
                    'log_action' => $log_action,
                    'vcc_id' => isset($result['vcc_id']) ? $result['vcc_id'] : 0,
                    'filename' => ''
                ))
            ));
        }

        $conn = $this->get('doctrine.dbal.default_connection');
        $table_id = empty($result['table_id']) ? 0 : $result['table_id'];
        $recordFile = $conn->fetchColumn(
            'SELECT address FROM win_sounds WHERE id = :sound_id LIMIT 1',
            array(':sound_id' => $table_id)
        );
        $flysystem = $this->get("icsoc_filesystem");
        if (!$flysystem->has($recordFile)) {
            return new Response('', Response::HTTP_NOT_FOUND, array(
                'X-Cti-Sync-Type' => 'sound',
                'X-Cti-Sync' => json_encode(array(
                    'log_action' => $log_action,
                    'vcc_id' => isset($result['vcc_id']) ? $result['vcc_id'] : 0,
                    'filename' => $recordFile
                ))
            ));
        }
        $fileType = $this->getSoundFileType($recordFile);
        try {
            $ossFileType = $flysystem->getMimetype($recordFile);
            $this->get("logger")->info(sprintf("文件%s,Sound_mimeType:【%s】;OssMimeType【%s】", $recordFile, $fileType, $ossFileType));
            $content = $flysystem->read($recordFile);
        } catch (\Exception $e) {
            $this->get('logger')->error($e->getMessage());
        }

        return new Response($content, Response::HTTP_OK, array(
            'Pragma' => 'Public',
            'Expires' => 0,
            'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-type' => $fileType,
            'Content-Length' => $flysystem->getSize($recordFile),
            'Content-Transfer-Encoding' => 'binary',
            'Accept-Ranges' => 'bytes',
            'Content-Disposition' => 'attachment;filename='.basename($recordFile),
            'X-Cti-Sync-Type' => 'sound',
            'X-Cti-Sync' => json_encode(array(
                'log_action' => $log_action,
                'vcc_id' => isset($result['vcc_id']) ? $result['vcc_id'] : 0,
                'filename' => basename($recordFile)
            ))
        ));

        /*
        if (!file_exists($recordFile)) {
            return new Response('', Response::HTTP_NOT_FOUND, array(
                'X-Cti-Sync-Type' => 'sound',
                'X-Cti-Sync' => json_encode(array(
                    'log_action' => $log_action,
                    'vcc_id' => isset($result['vcc_id']) ? $result['vcc_id'] : 0,
                    'filename' => $recordFile
                ))
            ));
        }*/
        /*
        $fileType = $this->getSoundFileType($recordFile);
        return new Response(file_get_contents($recordFile), Response::HTTP_OK, array(
            'Pragma' => 'Public',
            'Expires' => 0,
            'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-type' => $fileType,
            'Content-Length' => filesize($recordFile),
            'Content-Transfer-Encoding' => 'binary',
            'Accept-Ranges' => 'bytes',
            'Content-Disposition' => 'attachment;filename='.basename($recordFile),
            'X-Cti-Sync-Type' => 'sound',
            'X-Cti-Sync' => json_encode(array(
                'log_action' => $log_action,
                'vcc_id' => isset($result['vcc_id']) ? $result['vcc_id'] : 0,
                'filename' => basename($recordFile)
            ))
        ));*/
    }

    /**
     * 查询文件类型
     *
     * @param string $file 语音文件
     *
     * @return string 文件类型
     */
    public function getSoundFileType($file)
    {
        $extend = pathinfo($file);
        $extend = empty($extend['extension']) ? '' : strtolower($extend['extension']);
        if ($extend == 'mp3') {
            return 'audio/mp3';
        } elseif ($extend == 'wav') {
            return 'audio/x-wav';
        } else {
            return '';
        }
    }
}
